package club.xyes.zkh.ecommerce.wechat.util.crypt;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.util.Base64Utils;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.util.Arrays;

/**
 * Create by 郭文梁 2019/4/28 0028 17:31
 * WXBizDataCrypt
 * 微信相关数据解码器
 *
 * @author 郭文梁
 * @data 2019/4/28 0028
 */
public class WxBizDataCrypt {
    private Key key;
    private Cipher cipher;

    public WxBizDataCrypt(String sessionKey) {
        byte[] sessionKeyBytes = Base64Utils.decodeFromString(sessionKey);
        int base = 16;
        if (sessionKeyBytes.length % base != 0) {
            int groups = sessionKeyBytes.length / base + 1;
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(sessionKeyBytes, 0, temp, 0, sessionKeyBytes.length);
            sessionKeyBytes = temp;
        }
        // 初始化
        Security.addProvider(new BouncyCastleProvider());
        // 转化成JAVA的密钥格式
        key = new SecretKeySpec(sessionKeyBytes, "AES");
        try {
            // 初始化cipher
            cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 解码
     *
     * @param iv            初始向量
     * @param encryptedData 加密数据
     * @return 解密结果
     */
    public String decode(String iv, String encryptedData) {
        byte[] ivBytes = Base64Utils.decodeFromString(iv);
        byte[] dataBytes = Base64Utils.decodeFromString(encryptedData);
        String encryptedText;
        try {
            cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(ivBytes));
            encryptedText = new String(cipher.doFinal(dataBytes));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return encryptedText;
    }
}
